package com.liu.tools.conf;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

/**
 * @DateTime 2014年12月18日 下午3:51:27
 * @Company 华视传媒
 * @Author 刘兴密
 * @QQ 63972012
 * @Desc 自定义日志文件加载路径类
 */
public class LogBackConfigLoader {
	
	private static Logger log = LoggerFactory.getLogger(LogBackConfigLoader.class);
	
	public static final String CONFIG_LOGBACK_PARAM = "configLogbackParam";
	
	/**
	 * @DateTime 2014年12月18日 下午3:51:58
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 加载日志文件
	 * @param servletContext
	 * @throws IOException
	 * @throws JoranException
	 * void
	 */
	public static void load (ServletContext servletContext) throws IOException, JoranException{  
	       
		    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();  
	        
	        String configFileName = servletContext.getInitParameter(CONFIG_LOGBACK_PARAM);
	        
	        String path = LocalConfig.configPath + configFileName;
	        
	        File externalConfigFile = new File(path);  
	        if(!externalConfigFile.exists()){  
	            throw new IOException("Logback External Config File Parameter does not reference a file that exists");  
	        }else{  
	            if(!externalConfigFile.isFile()){  
	                throw new IOException("Logback External Config File Parameter exists, but does not reference a file");  
	            }else{  
	                if(!externalConfigFile.canRead()){  
	                    throw new IOException("Logback External Config File exists and is a file, but cannot be read.");  
	                }else{  
	                    JoranConfigurator configurator = new JoranConfigurator();  
	                    configurator.setContext(lc);  
	                    lc.reset();  
	                    configurator.doConfigure(path);  
	                    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);  
	                    log.info("Logback file loading  path:" + path);
	                }  
	            }     
	        }  
	    } 
}
